package com.wnxy.sddfp.system.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.conf.HystrixPropertiesManager;
import com.wnxy.sddfp.common.exception.BusinessException;
import com.wnxy.sddfp.common.result.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/test")
public class TestController {

    /**
     * 测试路径：http://localhost:9010/test/list
     */
    @GetMapping("/list")
    public String list(HttpServletRequest request) {
        String userId = request.getHeader("userId");
        System.out.println(userId);
        return "list";
    }

    /**
     * 测试降级方法
     */
    @GetMapping("/hystrix/{id}")
    @HystrixCommand(fallbackMethod = "fallbackTest",commandProperties = {
            // 是否开启断路器
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED,value = "true"),
            // 请求错误率大于 50% 就启动熔断器
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE,value = "50"),
            // 默认10秒内访问接口达到20次，且错误率大于50%则打开断路器，触发熔断； 为了方便测试，这里修改请求数为10
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD,value = "10"),
            //断路多久以后开始尝试是否恢复，默认5s
            @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS,value = "10000")
    })
    public Result hystrixTest(@PathVariable("id")Integer id) {
        if (id < 10) {
            throw new BusinessException();
        }
        return Result.ok();
    }

    // 降级方法，必须与@HystrixCommand修饰的方法的参数、返回类型一样
    public Result fallbackTest(@PathVariable("id")Integer id) {
        return Result.fail("服务降级方法");
    }
}
